'''
项目服务模块，提供项目管理相关功能
'''
from flask import g
from psycopg2.extras import RealDictCursor

def get_project_by_id(project_id):
    """
    通过项目ID获取项目详情
    
    Args:
        project_id: 项目ID
        
    Returns:
        dict: 项目详情，如果项目不存在返回None
    """
    if not project_id:
        return None
        
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    SELECT * FROM projects 
    WHERE id = %s AND status != 'deleted'
    ''', (project_id,))
    
    project = cursor.fetchone()
    return project

def get_projects_by_tenant(tenant_id):
    """
    获取指定租户的所有项目
    
    Args:
        tenant_id: 租户ID
        
    Returns:
        list: 项目列表
    """
    if not tenant_id:
        return []
        
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    SELECT * FROM projects 
    WHERE tenant_id = %s AND status != 'deleted'
    ORDER BY created_at DESC
    ''', (tenant_id,))
    
    projects = cursor.fetchall()
    return projects

def create_project(name, description, tenant_id):
    """
    创建新项目
    
    Args:
        name: 项目名称
        description: 项目描述
        tenant_id: 租户ID
        
    Returns:
        dict: 新创建的项目详情
    """
    if not name or not tenant_id:
        return None
        
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    INSERT INTO projects (name, description, tenant_id)
    VALUES (%s, %s, %s)
    RETURNING *
    ''', (name, description, tenant_id))
    
    new_project = cursor.fetchone()
    conn.commit()
    
    return new_project

def update_project(project_id, data):
    """
    更新项目信息
    
    Args:
        project_id: 项目ID
        data: 要更新的字段字典
        
    Returns:
        dict: 更新后的项目详情，如果项目不存在返回None
    """
    if not project_id or not data:
        return None
    
    # 过滤允许更新的字段
    allowed_fields = ['name', 'description', 'status']
    update_data = {k: v for k, v in data.items() if k in allowed_fields}
    
    if not update_data:
        return None
        
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 构建更新SQL
    set_clause = ', '.join([f"{field} = %s" for field in update_data.keys()])
    query = f'''
    UPDATE projects 
    SET {set_clause}, updated_at = CURRENT_TIMESTAMP
    WHERE id = %s
    RETURNING *
    '''
    
    # 构建参数
    params = list(update_data.values())
    params.append(project_id)
    
    cursor.execute(query, params)
    updated_project = cursor.fetchone()
    
    if updated_project:
        conn.commit()
    
    return updated_project

def delete_project(project_id):
    """
    删除项目（软删除）
    
    Args:
        project_id: 项目ID
        
    Returns:
        bool: 是否删除成功
    """
    if not project_id:
        return False
        
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    UPDATE projects 
    SET status = 'deleted', updated_at = CURRENT_TIMESTAMP
    WHERE id = %s
    RETURNING id
    ''', (project_id,))
    
    result = cursor.fetchone()
    
    if result:
        conn.commit()
        return True
    
    return False 